﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mengsk.ProxyDelivery.App.Extenstions;
using System.IO;
using System.Runtime.ExceptionServices;
using Seagull.BarTender.Print;
using Mengsk.ProxyDelivery.App.Domain;
using Mengsk.ProxyDelivery.App.Device;

namespace Mengsk.ProxyDelivery.App.UI.Order
{
    /// <summary>
    /// OrderAllUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class OrderAllUserControl : UserControl, IPlugin
    {
        private bool myLoaded = false;

        private const int QUERY_TYPE_ID = 1;
        private const int QUERY_TYPE_RETURNDELIVERYNUMBER = 2;
        private const int QUERY_TYPE_OTHER = 3;

        private int currentQueryType = 0;
        private OrderService orderService = ServiceContainer.GetService<OrderService>();
        private VendorService vs = ServiceContainer.GetService<VendorService>();
        public OrderAllUserControl()
        {
            InitializeComponent();
        }

        public string Title
        {
            get { return "所有订单"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.cbbPopPayType.Bind<OrderPopPayType>();
            this.cbbState.Bind<OrderState>();
            this.myLoaded = true;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string strId = this.tbId.Text.Trim();

            string strPopBuyerId = this.tbBuyName.Text.Trim();
            string strReceiverName = this.tbReceiverName.Text.Trim();
            string strReceiverPhone = this.tbReceiverPhone.Text.Trim();
            string strDeliveryNumber = this.tbDeliveryNumber.Text.Trim();
            string strReceiverAddress = this.tbAddress.Text.Trim();
            string strNumber = this.tbNumber.Text.Trim();
            string strReceiverMobile = this.tbReceiverMobile.Text.Trim();
            int state = (int)this.cbbState.GetSelectedEnum<OrderState>();
            int popPayType = this.cbbPopPayType.SelectedIndex;
            int popType = 0;
            int needMoreMoney = this.cbbNeedMoreMoney.SelectedIndex - 1;
            DateTime start = this.dpStart.Value == null ? DateTime.MinValue : this.dpStart.Value.Value;
            DateTime end = this.dpEnd.Value == null ? DateTime.MinValue : this.dpEnd.Value.Value;
            int sellerId = 0;
            int.TryParse(this.tbSellerId.Text.Trim(), out sellerId);
            this.pbBar.Parameters.Clear();
            try
            {
                if (string.IsNullOrWhiteSpace(strId) == false)
                {
                    long orderId = 0;
                    orderId = long.Parse(strId);
                    if (orderId > 0)
                    {
                        this.pbBar.Parameters.Add("id", orderId);
                        this.currentQueryType = QUERY_TYPE_ID;
                        this.pbBar.StartPage();
                        return;
                    }
                }

                pbBar.Parameters.Add("sellerId", sellerId);
                pbBar.Parameters.Add("popBuyerId", strPopBuyerId);
                pbBar.Parameters.Add("receiverName", strReceiverName);
                pbBar.Parameters.Add("receiverPhone", strReceiverPhone);
                pbBar.Parameters.Add("receiverAddress", strReceiverAddress);
                pbBar.Parameters.Add("deliveryNumber", strDeliveryNumber);
                pbBar.Parameters.Add("state", state);
                pbBar.Parameters.Add("popPayType", popPayType);
                pbBar.Parameters.Add("popType", popType);
                pbBar.Parameters.Add("needMoreMoney", needMoreMoney);
                pbBar.Parameters.Add("start", start);
                pbBar.Parameters.Add("end", end);
                pbBar.Parameters.Add("number", strNumber);
                pbBar.Parameters.Add("receiverMobile", strReceiverMobile);
                pbBar.Parameters.Add("timeType", this.cbbTimeType.SelectedIndex + 1);
                this.currentQueryType = QUERY_TYPE_OTHER;
                this.pbBar.StartPage();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void closeOrder_Click(object sender, RoutedEventArgs e)
        {

        }

        [HandleProcessCorruptedStateExceptions]
        private void pbBar_PageChanging(object sender, PageBar.PageChangeEventArgs e)
        {
            try
            {
                DataCollection<Mengsk.ProxyDelivery.Domain.Order> data = null;
                if (this.currentQueryType == QUERY_TYPE_ID)
                {
                    Mengsk.ProxyDelivery.Domain.Order order = this.orderService.GetById(e.GetParameter<long>("id"));
                    data = new DataCollection<ProxyDelivery.Domain.Order>();
                    data.Total = order == null ? 0 : 1;
                    data.Datas = new List<Mengsk.ProxyDelivery.Domain.Order>();
                    if (order != null)
                    {
                        data.Datas.Add(order);
                    }
                }
                else if (this.currentQueryType == QUERY_TYPE_RETURNDELIVERYNUMBER)
                {
                    data = this.orderService.GetByDelieryInNumber(e.GetParameter<string>("deliveryNumber"));
                }
                else if (this.currentQueryType == QUERY_TYPE_OTHER)
                {
                    data = this.orderService.GetByAll(e.GetParameter<int>("sellerId"), e.GetParameter<string>("popBuyerId"), e.GetParameter<string>("receiverPhone"), e.GetParameter<string>("receiverMobile")
                        , e.GetParameter<string>("receiverName"), e.GetParameter<string>("receiverAddress"), e.GetParameter<string>("deliveryNumber"), e.GetParameter<string>("number"), e.GetParameter<int>("state"), e.GetParameter<int>("popPayType"),
                        e.GetParameter<int>("popType"), e.GetParameter<int>("needMoreMoney"), e.GetParameter<int>("timeType"), e.GetParameter<DateTime>("start"), e.GetParameter<DateTime>("end"), e.CurrentPage - 1, e.PageSize);

                }

                this.pbBar.Total = data.Total;
                this.pbBar.CurrentCount = data.Datas.Count;
                this.tbTotalMoney.Text = "当前页金额：" + data.Datas.Select(obj => obj.TotalMoney).Sum();
                this.lstItems.ItemsSource = data.Datas.Select(new Func<ProxyDelivery.Domain.Order, OrderViewModel>(obj => new OrderViewModel(obj))).ToArray();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null || btn.Tag == null || btn.Tag is Mengsk.ProxyDelivery.Domain.Order == false)
                {
                    return;
                }
                OrderDetailWindow window = new OrderDetailWindow { DataContext = btn.Tag };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDeliveryNumber_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null)
                {
                    return;
                }
                var order = btn.Tag as OrderViewModel;
                if (order == null)
                {
                    throw new Exception("Tag为空或者类型不正确");
                }
                if (string.IsNullOrWhiteSpace(order.Source.DeliveryCompany) || string.IsNullOrWhiteSpace(order.Source.DeliveryNumber))
                {
                    return;
                }
                Delivery.DeliveryQueryWindow window = new Delivery.DeliveryQueryWindow { DeliveryCompany = order.Source.DeliveryCompany, DeliveryNumber = order.Source.DeliveryNumber };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private static string FormatCSVContent(params string[] values)
        {
            if (values == null || values.Length == 0)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < values.Length; i++)
            {
                sb.Append("\"");
                if (values[i] == null)
                {
                    values[i] = "";
                }
                sb.Append(values[i].Replace("\"", "\"\""));//双引号，需要转义
                sb.Append("\",");
            }
            sb.Length = sb.Length - 1;//支最后一个 , 号
            sb.AppendLine();//增加换行
            return sb.ToString();
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var orderVm = this.lstItems.ItemsSource as OrderViewModel[];
                if (orderVm == null || orderVm.Length < 1)
                {
                    MessageBox.Show("没有需要导出的商品");
                    return;
                }

                var orders = orderVm.Select(obj => obj.Source).ToArray();

                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.AddExtension = true;
                sfd.Filter = "*.csv|CSV文件";
                sfd.FileName = "奇牛订单商品导出" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".csv";
                bool? ret = sfd.ShowDialog();
                if (ret == false || ret.Value == false)
                {
                    return;
                }
                if (File.Exists(sfd.FileName))
                {
                    File.Delete(sfd.FileName);
                }
                VendorService vs = ServiceContainer.GetService<VendorService>();
                //添加头部
                File.AppendAllText(sfd.FileName, FormatCSVContent("订单编号", "卖家编号", "创建时间", "付款时间", "门牌", "厂家货号", "颜色尺码", "价格", "数量", "版本"), Encoding.Default);
                foreach (var order in orders)
                {
                    if (order.OrderGoodss == null)
                    {
                        continue;
                    }

                    foreach (OrderGoods og in order.OrderGoodss)
                    {
                        var vendor = vs.GetByName(og.Vendor);
                        if (vendor == null || vendor.Count < 1)
                        {
                            MessageBox.Show("厂家不存在");
                            continue;
                        }
                        if (vendor.Count > 1)
                        {
                            MessageBox.Show("找到多个厂家");
                        }
                        File.AppendAllText(sfd.FileName, FormatCSVContent(order.Id.ToString(), order.SellerId.ToString(), order.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), order.PayTime.ToString("yyyy-MM-dd HH:mm:ss"), VendorService.FormatVendorDoor(vendor[0].MarketAddress), og.Vendor + " " + og.Number, "颜色:" + og.Color + "|" + "尺码:" + og.Size, ((int)(og.Price + og.AddPrice)).ToString(), og.Count.ToString(), og.Edtion), Encoding.Default);
                    }
                }
                MessageBox.Show(sfd.FileName, "已成功导出");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnExportAll_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnSetPrice_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement btn = sender as FrameworkElement;
                if (btn == null)
                {
                    MessageBox.Show("事件源对不是 btnSetPrice_Click FrameworkElement");
                    return;
                }
                var orderGoods = btn.Tag as OrderGoods;
                if (orderGoods == null)
                {
                    throw new Exception("Tag 为空或者类型不正确");
                }

                if (this.orderService.IsOrderGoodsValid(orderGoods.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }
                OrderGoodsPriceEditWindow win = new OrderGoodsPriceEditWindow() { OrderGoods = btn.Tag as OrderGoods };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnSetPrice_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                FrameworkElement btn = sender as FrameworkElement;
                if (btn == null)
                {
                    MessageBox.Show("事件源对不是 btnSetPrice_Click FrameworkElement");
                    return;
                }

                var orderGoods = btn.Tag as OrderGoods;
                if (orderGoods == null)
                {
                    throw new Exception("Tag 为空或者类型不正确");
                }

                if (this.orderService.IsOrderGoodsValid(orderGoods.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderGoodsPriceEditWindow win = new OrderGoodsPriceEditWindow() { OrderGoods = orderGoods };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCloseOrderGoods_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnCloseOrder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不正确");
                    return;
                }

                var order = fe.Tag as OrderViewModel;
                if (order == null)
                {
                    MessageBox.Show("没有需要关闭的订单");
                    return;
                }

                OrderCloseWindow win = new OrderCloseWindow { Order = order.Source };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不正确");
                    return;
                }

                var orderGoods = fe.Tag as Mengsk.ProxyDelivery.Domain.OrderGoods;
                if (orderGoods == null)
                {
                    MessageBox.Show("没有需要关闭的订单");
                    return;
                }

                if (this.orderService.IsOrderGoodsValid(orderGoods.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderGoodsEditWindow win = new OrderGoodsEditWindow { OrderGoods = orderGoods };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModifyDeliveryInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement btn = sender as FrameworkElement;
                if (btn == null)
                {
                    MessageBox.Show("事件源对不是 btnSetPrice_Click FrameworkElement");
                    return;
                }
                OrdeModifyDeliveryInfoWindow win = new OrdeModifyDeliveryInfoWindow() { Order = btn.Tag as Mengsk.ProxyDelivery.Domain.Order };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GoodsImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    return;
                }

                if (fe.Tag == null)
                {
                    return;
                }
                int numberId = (int)fe.Tag;
                if (numberId <= 0)
                {
                    return;
                }
                Shoes s = ServiceContainer.GetService<ShoesService>().GetById(numberId);
                if (s == null)
                {
                    MessageBox.Show("无法获取指定的商品");
                    return;
                }
                if (string.IsNullOrWhiteSpace(s.Url))
                {
                    return;
                }
                Process.Start(s.Url);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCopyStock_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不正确");
                    return;
                }

                var orderGoods = fe.Tag as Mengsk.ProxyDelivery.Domain.OrderGoods;
                if (orderGoods == null)
                {
                    MessageBox.Show("没有需要关闭的订单");
                    return;
                }

                Clipboard.SetText(orderGoods.Vendor + " " + orderGoods.Edtion + " " + orderGoods.Number + " " + orderGoods.Color + " " + orderGoods.Size);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCreateRefund_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不正确");
                    return;
                }

                var orderGoods = fe.Tag as Mengsk.ProxyDelivery.Domain.OrderGoods;
                if (orderGoods == null)
                {
                    MessageBox.Show("没有需要关闭的订单");
                    return;
                }

                if (this.orderService.IsOrderGoodsValid(orderGoods.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderGoodsCreateReturn win = new OrderGoodsCreateReturn { OrderGoods = orderGoods };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tbDeliveryNumber_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            try
            {
                this.btnSearch_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                e.Handled = true;
                this.Dispatcher.BeginInvoke(new Action(() => this.tbDeliveryNumber.SelectAll()));
            }
        }

        private void btnModifyStock_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不正确");
                    return;
                }

                var orderGoods = fe.Tag as Mengsk.ProxyDelivery.Domain.OrderGoods;
                if (orderGoods == null)
                {
                    MessageBox.Show("没有需要关闭的订单");
                    return;
                }

                if (this.orderService.IsOrderGoodsValid(orderGoods.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderGoodsStockModifyWindow win = new OrderGoodsStockModifyWindow { OrderGoods = orderGoods };
                if (win.ShowDialog().Value == true)
                    this.RefreshItems();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void RefreshItems()
        {
            var items = this.lstItems.ItemsSource;
            this.lstItems.ItemsSource = null;
            this.lstItems.ItemsSource = items;
        }


        private void chkCheckAll_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                var items = this.lstItems.ItemsSource as OrderViewModel[];
                if (items == null)
                {
                    return;
                }
                foreach (var item in items)
                {
                    item.IsChecked = this.chkCheckAll.IsChecked.Value;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCopyDelivery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    throw new Exception("事件源不是 FrameworkElement");
                }

                string number = fe.Tag as string;
                if (string.IsNullOrWhiteSpace(number))
                {
                    throw new Exception("快递单号为空");
                }
                Clipboard.SetText(number);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSpilteOrder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    throw new Exception("事件源不是FrameworkElement");
                }
                OrderViewModel vm = fe.Tag as OrderViewModel;
                if (vm == null)
                {
                    throw new Exception("Tag 数据为空或者类型不对");
                }

                if (this.orderService.IsOrderGoodsValid(vm.Source.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderSpilteWindow window = new OrderSpilteWindow { Order = vm.Source };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModifyReceiverInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    throw new Exception("事件源不是FrameworkElement");
                }
                OrderViewModel vm = fe.Tag as OrderViewModel;
                if (vm == null)
                {
                    throw new Exception("Tag 数据为空或者类型不对");
                }

                if (this.orderService.IsOrderGoodsValid(vm.Source.State) == false)
                {
                    throw new Exception("订单状态不正确");
                }

                OrderReceiverInfoModifyWindow window = new OrderReceiverInfoModifyWindow { Order = vm.Source };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnAddOrderGoods_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    throw new Exception("事件源不是FrameworkElement");
                }
                OrderViewModel vm = fe.Tag as OrderViewModel;
                if (vm == null)
                {
                    throw new Exception("Tag 数据为空或者类型不对");
                }

                OrderEditWindow v = new OrderEditWindow { Order = vm.Source };
                v.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModifyComment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    throw new Exception("事件源不是FrameworkElement");
                }
                OrderViewModel vm = fe.Tag as OrderViewModel;
                if (vm == null)
                {
                    throw new Exception("Tag 数据为空或者类型不对");
                }
                var window = new MessageInput { Width = 1000, Title = "编辑描述", InputContent = vm.Source.SysComment };
                bool? ret = window.ShowDialog();
                if (ret == null || ret.Value == false)
                {
                    return;
                }

                this.orderService.ModifySystemComment(vm.Source.Id, window.InputContent);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
